import { Injectable, Inject } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { User, Auth } from '../domain/index';

@Injectable()
export class AuthService {
    private readonly domain = 'users';
    private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    private token = 'eyJhbGciQiJIUzI1NiIsInR5cCI6IkpXVCJ9' +
        '.eyJzdWIiOiIxMjM0NTY30dKWIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW41OnRydWV9' +
        '.TjVA95OrM7E2cBab3oRMHrHDcEfxjoYZgeFONFh7HgG';
    constructor(
        @Inject('BASE_CONFIG') private config,
        private http: HttpClient) { }

    regisiter(user: User): Observable<Auth> {
        console.log('user', user);
        const uri = `${this.config.uri}/${this.domain}`;
        return this.http
            .get<User[]>(uri, { params: { 'email': user.email } })
            .switchMap(res => {
                console.log('res', res);
                if (res.length > 0) {
                    throw new Error('user existed');
                }
                return this.http
                    .post(uri, JSON.stringify(user), { headers: this.headers })
                    .map(r => ({ token: this.token, user: r }) as Auth);
            });
    }
    login(username: string, password: string): Observable<Auth> {
        const uri = `${this.config.uri}/${this.domain}`;
        return this.http
            .get<User[]>(uri, { params: { eamil: username, password: password } })
            .map(res => {
                if (res.length === 0) {
                    throw new Error('username or password not match');
                }
                return {
                    token: this.token,
                    user: res[0]
                };
            });
    }
}
